<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="style.css">
    <script src="js/jquery.js"></script>
    <script src="js/template-web.js"></script>
    <script type="text/javascript">
        /*-------------------------- +
          获取id, class, tagName
         +-------------------------- */
        var get = {
            byId: function (id) {
                return typeof id === "string" ? document.getElementById(id) : id
            },
            byClass: function (sClass, oParent) {
                var aClass = [];
                var reClass = new RegExp("(^| )" + sClass + "( |$)");
                var aElem = this.byTagName("*", oParent);
                for (var i = 0; i < aElem.length; i++) reClass.test(aElem[i].className) && aClass.push(aElem[i]);
                return aClass
            },
            byTagName: function (elem, obj) {
                return (obj || document).getElementsByTagName(elem)
            }
        };
        /*-------------------------- +
          事件绑定, 删除
         +-------------------------- */
        var EventUtil = {
            addHandler: function (oElement, sEvent, fnHandler) {
                oElement.addEventListener ? oElement.addEventListener(sEvent, fnHandler, false) : (oElement["_" + sEvent + fnHandler] = fnHandler, oElement[sEvent + fnHandler] = function () { oElement["_" + sEvent + fnHandler]() }, oElement.attachEvent("on" + sEvent, oElement[sEvent + fnHandler]))
            },
            removeHandler: function (oElement, sEvent, fnHandler) {
                oElement.removeEventListener ? oElement.removeEventListener(sEvent, fnHandler, false) : oElement.detachEvent("on" + sEvent, oElement[sEvent + fnHandler])
            },
            addLoadHandler: function (fnHandler) {
                this.addHandler(window, "load", fnHandler)
            }
        };
        /*-------------------------- +
          设置css样式
          读取css样式
         +-------------------------- */
        function css(obj, attr, value) {
            switch (arguments.length) {
                case 2:
                    if (typeof arguments[1] == "object") {
                        for (var i in attr) i == "opacity" ? (obj.style["filter"] = "alpha(opacity=" + attr[i] + ")", obj.style[i] = attr[i] / 100) : obj.style[i] = attr[i];
                    }
                    else {
                        return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
                    }
                    break;
                case 3:
                    attr == "opacity" ? (obj.style["filter"] = "alpha(opacity=" + value + ")", obj.style[attr] = value / 100) : obj.style[attr] = value;
                    break;
            }
        };

        EventUtil.addLoadHandler(function () {
            var oMsgBox = get.byId("msgBox");
            var oUserName = get.byId("userName");
            var oConBox = get.byId("conBox");
            var oSendBtn = get.byId("sendBtn");
            var oMaxNum = get.byClass("maxNum")[0];
            var oCountTxt = get.byClass("countTxt")[0];
            var oList = get.byClass("list")[0];
            var oUl = get.byTagName("ul", oList)[0];
            var aLi = get.byTagName("li", oList);
            var aFtxt = get.byClass("f-text", oMsgBox);
            var aImg = get.byTagName("img", get.byId("face"));
            var bSend = false;
            var timer = null;
            var oTmp = "";
            var i = 0;
            var maxNum = 140;

            //禁止表单提交
            EventUtil.addHandler(get.byTagName("form", oMsgBox)[0], "submit", function () { return false });

            // //为广播按钮绑定发送事件
            // EventUtil.addHandler(oSendBtn, "click", fnSend);

            // //为Ctrl+Enter快捷键绑定发送事件
            // EventUtil.addHandler(document, "keyup", function (event) {
            //     var event = event || window.event;
            //     event.ctrlKey && event.keyCode == 13 && fnSend()
            // });

            //发送广播函数
            // function fnSend() {
            //     var reg = /^\s*$/g;
            //     if (reg.test(oUserName.value)) {
            //         alert("\u8bf7\u586b\u5199\u60a8\u7684\u59d3\u540d");
            //         oUserName.focus()
            //     }
            //     else if (!/^[u4e00-\u9fa5\w]{2,8}$/g.test(oUserName.value)) {
            //         alert("\u59d3\u540d\u75312-8\u4f4d\u5b57\u6bcd\u3001\u6570\u5b57\u3001\u4e0b\u5212\u7ebf\u3001\u6c49\u5b57\u7ec4\u6210\uff01");
            //         oUserName.focus()
            //     }
            //     else if (reg.test(oConBox.value)) {
            //         alert("\u968f\u4fbf\u8bf4\u70b9\u4ec0\u4e48\u5427\uff01");
            //         oConBox.focus()
            //     }
            //     else if (!bSend) {
            //         alert("\u4f60\u8f93\u5165\u7684\u5185\u5bb9\u5df2\u8d85\u51fa\u9650\u5236\uff0c\u8bf7\u68c0\u67e5\uff01");
            //         oConBox.focus()
            //     }
            //     else {
                    
            //     }
            // };

            //事件绑定, 判断字符输入
            EventUtil.addHandler(oConBox, "keyup", confine);
            EventUtil.addHandler(oConBox, "focus", confine);
            EventUtil.addHandler(oConBox, "change", confine);

            //输入字符限制
            function confine() {
                var iLen = 0;
                for (i = 0; i < oConBox.value.length; i++) iLen += /[^\x00-\xff]/g.test(oConBox.value.charAt(i)) ? 1 : 0.5;
                oMaxNum.innerHTML = Math.abs(maxNum - Math.floor(iLen));
                maxNum - Math.floor(iLen) >= 0 ? (css(oMaxNum, "color", ""), oCountTxt.innerHTML = "\u8fd8\u80fd\u8f93\u5165", bSend = true) : (css(oMaxNum, "color", "#f60"), oCountTxt.innerHTML = "\u5df2\u8d85\u51fa", bSend = false)
            }
            //加载即调用
            confine();

            //广播按钮鼠标划过样式
            EventUtil.addHandler(oSendBtn, "mouseover", function () { this.className = "hover" });

            //广播按钮鼠标离开样式
            EventUtil.addHandler(oSendBtn, "mouseout", function () { this.className = "" });

            //输入框获取焦点时样式
            for (i = 0; i < aFtxt.length; i++) {
                EventUtil.addHandler(aFtxt[i], "focus", function () { this.className = "active" });
                EventUtil.addHandler(aFtxt[i], "blur", function () { this.className = "" })
            }

            //格式化时间, 如果为一位数时补0
            function format(str) {
                return str.toString().replace(/^(\d)$/, "0$1")
            }

            //头像
            for (i = 0; i < aImg.length; i++) {
                aImg[i].onmouseover = function () {
                    this.className += " hover"
                };
                aImg[i].onmouseout = function () {
                    this.className = this.className.replace(/\s?hover/, "")
                };
                aImg[i].onclick = function () {
                    for (i = 0; i < aImg.length; i++) aImg[i].className = "";
                    this.className = "current"
                }
            }
        });
    </script>
    <script type="text/html" id="message">
        <% for(var i=0 ; i< length ; i++){ %>
        <li uid="<%= $data[i].id %>">
            <div class="userPic"><img src=" <%= $data[i].pic %>" /></div>
            <div class="content">
                <div class="userName"><a href="javascript:;"> <%= $data[i].username %></a>:</div>
                <div class="msgInfo"><%= $data[i].content %></div>
                <div class="times"><span><%= $data[i].time %></span><a class="del" href="javascript:;">删除</a></div>
            </div>
        </li>
        <% } %>
    </script>
    <script>
        $(function () {
            const list = $('.list ul');
            const send_btn = $('#sendBtn');

            // 全部添加删除事件
            function attachDelete(){
                $('.del').click(function(){
                    var current_li = $(this).parent().parent().parent();
                    const id = current_li.attr("uid");
                    $.ajax({
                        url:"http://localhost:3000/comments/"+id,
                        method:"DELETE",
                        success: function(){
                            current_li.animate({height: "0px"},400,function(){
                                current_li.remove();
                            })
                        }
                    });
                   }) ;
            }

            //查询留言
            $.ajax({
                url: "http://localhost:3000/comments",
                success: function (data) {
                    list.html(template('message', data));
                    // 删除方法
                    attachDelete();
                }
            })
            
            // 添加留言
            send_btn.on('click', function () {
                const username = $('#userName').val();
                const content = $('#conBox').val();
                const time = new Date().toLocaleString();
                const pic = $('#face .current').attr("src");
                $.ajax({
                    url: "http://localhost:3000/comments",
                    method: "POST",
                    dataType: "JSON",
                    data: {
                        username: username,
                        content: content,
                        pic: pic,
                        time: time
                    },
                    success: function(data){
                        list.append(template('message', [data]));
                        $('#conBox').val('');
                        attachDelete();
                    }
                });
            });
        });

    </script>
</head>

<body>

    <div id="msgBox">
        <form>
            <h2>来 , 说说你在做什么 , 想什么</h2>

            <div>
                <label for="userName">用户名:</label>
                <input id="userName" class="f-text" value="" />
                <p id="face"><img src="img/face1.gif" class="current" /><img src="img/face2.gif" /><img
                        src="img/face3.gif" /><img src="img/face4.gif" /><img src="img/face5.gif" /><img
                        src="img/face6.gif" /><img src="img/face7.gif" /><img src="img/face8.gif" /></p>

            </div>
            <div>
                <label for="conBox">内容：</label>
                <textarea id="conBox" class="f-text"></textarea>
            </div>
            <div class="tr">
                <p>
                    <span class="countTxt">还能输入</span><strong class="maxNum">140</strong><span>个字</span>

                    <input id="sendBtn" type="button" value="" title="快捷键 Ctrl+Enter" />
                </p>
            </div>
        </form>
        <div class="list">
            <h3><span>大家在说</span></h3>
            <ul>
            </ul>
        </div>
    </div>

</body>

</html>